package utils

import (
	"regexp"
	"strings"
)

// DsnAnalysisDbName Dsn解析出数据库名称
func DsnAnalysisDbName(driver string, sqlConn string) string {
	dbName := ""
	if driver == "mysql" {
		reg, err := regexp.Compile("/(\\w+)")
		if err == nil {
			dbName = reg.FindStringSubmatch(sqlConn)[1]
		}
	}
	return dbName
}

// ToUpperCamelCase 大驼峰式命名法，例如：FirstName、LastName
func ToUpperCamelCase(name string) string {
	newStr := make([]rune, 0)
	upNextChar := true
	name = strings.ToLower(name)
	for _, chr := range name {
		switch {
		case upNextChar:
			upNextChar = false
			if 'a' <= chr && chr <= 'z' {
				chr -= 'a' - 'A'
			}
		case chr == '_':
			upNextChar = true
			continue
		}
		newStr = append(newStr, chr)
	}

	newName := strings.Replace(string(newStr), ".", "_", -1)
	return newName
}

// ToLowerCamelCase 小驼峰式命名法，例如：firstName、lastName
func ToLowerCamelCase(s string) string {
	data := make([]byte, 0, len(s))
	j := false
	k := false
	num := len(s) - 1
	for i := 0; i <= num; i++ {
		d := s[i]
		if k == false && d >= 'A' && d <= 'Z' {
			k = true
		}
		if d >= 'a' && d <= 'z' && (j || k == false) {
			if i != 0 {
				d = d - 32
			}
			j = false
			k = true
		}
		if k && d == '_' && num > i && s[i+1] >= 'a' && s[i+1] <= 'z' {
			j = true
			continue
		}
		data = append(data, d)
	}
	return string(data[:])
}

// MysqlToGoType Mysql数据类型转Go数据类型
func MysqlToGoType(columnType string) string {
	goType := ""
	switch columnType {
	case "bit", "tinyint", "smallint", "mediumint", "int", "integer", "serial":
		goType = "int32"
		break
	case "bigint", "bigserial":
		goType = "int64"
		break
	case "char", "varchar", "tinytext", "text", "mediumtext", "longtext", "json":
		goType = "string"
		break
	case "date", "datetime", "time", "timestamp":
		goType = "time.Time"
		break
	case "decimal", "numeric":
		goType = "float64"
		break
	case "real", "float":
		goType = "float64"
		break
	case "double":
		goType = "float64"
		break
	case "tinyblob", "blob", "mediumblob", "longblob", "bytea":
		goType = "string"
		break
	case "bool":
		goType = "bool"
		break
	default:
		goType = "string"
	}
	return goType
}
